package file

import (
	"github.com/bgmp/config"
	"github.com/bgmp/handler"
	"github.com/bgmp/model"
	"github.com/bgmp/service"
	"github.com/gin-gonic/gin"
	log "github.com/sirupsen/logrus"
	"io"
	"net/http"
)

func UploadFile(c *gin.Context) {
	name := c.Request.URL.Query().Get("Name")
	if name == "" {
		handler.ReplyError(c, http.StatusBadRequest, "参数[Name]未设置")
		return
	}

	// 二进制文件读取下来
	requestBody, err := io.ReadAll(c.Request.Body)
	if len(requestBody) <= 0 {
		handler.ReplyError(c, http.StatusBadRequest, "请勿传入空文件！")
		return
	}

	if err != nil {
		log.Error("failed to read request body file")
		handler.ReplyError(c, http.StatusInternalServerError, "failed to read request body")
		return
	}
	// 取唯一ID
	sid := service.NextId()
	fileType := c.GetHeader("Content-Type")

	link, err := service.UploadFile(sid.String(), requestBody, fileType)
	if err != nil {
		log.Error(err)
		handler.ReplyError(c, http.StatusInternalServerError, "保存文件失败")
		return
	}

	file := model.File{
		FileField: model.FileField{
			Sid:  sid,
			Name: name,
			Size: int64(len(requestBody)),
			Link: link,
			Type: fileType,
		},
	}
	err = file.Create(config.DB)
	if err != nil {
		log.Error(err)
		handler.ReplyError(c, http.StatusInternalServerError, "保存文件失败")
		return
	}

	handler.ReplyString(c, http.StatusOK, sid.String())
}
